package com.efast.cafe.portal.controller.company;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.controller.AbstractController;
import com.efast.cafe.framework.enums.ResultStatus;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.pager.Pagination;
import com.efast.cafe.framework.vo.CheckBoxTreeVo;
import com.efast.cafe.portal.bean.company.PortalCompanyRoleQueryBean;
import com.efast.cafe.portal.bean.company.PortalCompanyUserRoleBean;
import com.efast.cafe.portal.bean.company.PortalRolePurviewTree;
import com.efast.cafe.portal.entity.common.ModuleInfo;
import com.efast.cafe.portal.entity.common.ModuleMenu;
import com.efast.cafe.portal.entity.common.ModulePurview;
import com.efast.cafe.portal.entity.company.PortalCompanyRole;
import com.efast.cafe.portal.service.common.IResourceService;
import com.efast.cafe.portal.service.company.IPortalCompanyRoleService;
import com.efast.cafe.util.StringUtil;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/company")
@Api(description = "PortalCompanyRoleController", tags = {"角色管理"})
public class PortalCompanyRoleController extends AbstractController {
	@Autowired
	private IPortalCompanyRoleService portalCompanyRoleService;

	
	@Autowired
	private IResourceService portalResourceService;

	

	

	/**
	 * 企业角色列表分页查询
	 * 
	 * @param request
	 * @param response
	 * @param page
	 *            当前页
	 * @param rows
	 *            每页显示记录数
	 * @param sidx
	 *            排序字段
	 * @param sord
	 *            排序方式
	 * @return
	 * @throws JSONException
	 */
	@ApiOperation(value="分页查询角色列表")
	@RequestMapping(value = "/role/list",method= RequestMethod.POST)
	public @ResponseBody ResultBean roleList(HttpServletRequest request, HttpServletResponse response,
			@RequestBody PortalCompanyRoleQueryBean bean){
		Pagination<PortalCompanyRole> pager = super.initPager(bean.getStart() / bean.getLength() + 1, bean.getLength(),
				bean.getOrderBy(), bean.getSort());
		ResultBean result = new ResultBean(true, null);
		try {
			result.setObject(portalCompanyRoleService.queryPageRoleList(bean.getRoleName(), bean));
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}

	

	/**
	 * 企业角色编辑
	 * 
	 * @param request
	 * @param response
	 * @param portalCompanyRoleId
	 * @param roleName
	 * @param roleRemark
	 * @return
	 */
	@ApiOperation(value="编辑角色")
	@RequestMapping(value = "/role/edit",method= RequestMethod.POST)
	public @ResponseBody ResultBean roleEdit(HttpServletRequest request, HttpServletResponse response,
			@RequestBody PortalCompanyRoleQueryBean bean) {
		ResultBean result = new ResultBean(true, null);
		try {
			PortalCompanyRole role = new PortalCompanyRole();
			role.setPortalCompanyRoleId(bean.getPortalCompanyRoleId());
			role.setRoleName(bean.getRoleName());
			role.setRoleRemark(bean.getRoleRemark());
			role.setIsDefaultRole(bean.getIsDefaultRole());
			Long[] purviewIds = (Long[]) bean.getPurviewIds()
					.toArray(new Long[bean.getPurviewIds().size()]);
			portalCompanyRoleService.updateRole(role,purviewIds);
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}

		return result;

	}

	/**
	 * 企业角色新增
	 * 
	 * @param request
	 * @param response
	 * @param roleName
	 * @param roleRemark
	 * @return
	 */
	@ApiOperation(value="添加角色")
	@RequestMapping(value = "/role/add",method= RequestMethod.POST)
	public @ResponseBody ResultBean roleAdd(HttpServletRequest request, HttpServletResponse response,
			@RequestBody PortalCompanyRoleQueryBean bean) {
		ResultBean result = new ResultBean(true, null);
			PortalCompanyRole role = new PortalCompanyRole();
			role.setRoleName(bean.getRoleName());
			role.setRoleRemark(bean.getRoleRemark());
			role.setIsDefaultRole(bean.getIsDefaultRole());
			Long[] purviewIds = (Long[]) bean.getPurviewIds()
					.toArray(new Long[bean.getPurviewIds().size()]);
			portalCompanyRoleService.insertRole(role,purviewIds);
		

		return result;
	}

	/**
	 * 企业角色删除
	 * 
	 * @param roleId
	 * @return
	 */
	@ApiOperation(value="删除角色")
	@RequestMapping(value = "/role/del",method= RequestMethod.POST)
	public @ResponseBody ResultBean roleDel(@RequestBody PortalCompanyRoleQueryBean bean) {
		ResultBean result = new ResultBean(true, null);
		try {
			portalCompanyRoleService.deleteRole(bean.getPortalCompanyRoleId());
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}

		return result;
	}

	
	@ApiOperation(value="获取角色对应的权限树")
	@RequestMapping(value = "/role/purview_tree",method= RequestMethod.POST)
	public @ResponseBody ResultBean getModuleTreePurview(@RequestBody PortalCompanyRoleQueryBean bean) {
		ResultBean result = new ResultBean(true, null);
		try {
			List<CheckBoxTreeVo> voList = new ArrayList<CheckBoxTreeVo>();
			// 当前企业拥有的模块
			List<ModuleInfo> moduleList = portalResourceService.queryModulesByCompanyCode();
			List<String> check = new ArrayList<>();
			for (ModuleInfo moduleInfo : moduleList) {
				
					List<ModuleMenu> menuList = portalResourceService.queryMenus(moduleInfo.getModuleInfoId());
					List<ModulePurview> purviewList = portalResourceService
							.queryPurviewByCompanyCode(moduleInfo.getModuleInfoId());
					HashSet<Long> hasPur = null;
					if(bean.getPortalCompanyRoleId()!=null){
						hasPur = portalCompanyRoleService.queryPurviewByRole(bean.getPortalCompanyRoleId());
					}else{
						hasPur = new HashSet<>();
					}
					
					List<String> checkList = new ArrayList<String>();
					if(!check.contains(moduleInfo.getModuleCode())){
						check.add(moduleInfo.getModuleCode());
					for (ModuleMenu m : menuList) {
						CheckBoxTreeVo v = new CheckBoxTreeVo();
						v.setName(m.getMenuName());
						v.setIsChecked(false);
						v.setParentId(m.getParentId() == 0 ? "" : "menu_" + m.getParentId());
						v.setPId("menu_" + m.getModuleMenuId());
						voList.add(v);

					}
					}
					for (ModulePurview p : purviewList) {
						CheckBoxTreeVo v = new CheckBoxTreeVo();
						v.setName(p.getPurName());
						v.setIsChecked(hasPur.contains(p.getModulePurviewId()));
						v.setParentId("menu_" + p.getModuleMenuId());
						v.setPId(p.getModulePurviewId() + "");
						if (!checkList.contains(v.getPId())) {
							voList.add(v);
							checkList.add(v.getPId());
						}

					}
				}
				

			// 对voList进行处理构造树

			List<PortalRolePurviewTree> listTree = new ArrayList<>();
			for (int i = 0; i < voList.size(); i++) {
				PortalRolePurviewTree tree = new PortalRolePurviewTree();
				voList.get(i).setChecked(voList.get(i).getIsChecked());
				tree.setTitle(voList.get(i).getTitle());
				tree.setData(voList.get(i));
				listTree.add(tree);
			}
			// CheckBoxTreeVo root=getAreaTree(voList);
			result.setObject(listTree);
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}

	
	@RequestMapping(value = "/role/savePurview",method= RequestMethod.POST)
	public @ResponseBody ResultBean savePurview(@RequestBody PortalCompanyUserRoleBean portalCompanyUserRoleBean) {
		ResultBean result = new ResultBean(true, null);
		try {
			Long[] purviewIds = (Long[]) portalCompanyUserRoleBean.getPurviewIds()
					.toArray(new Long[portalCompanyUserRoleBean.getPurviewIds().size()]);

			portalCompanyRoleService.saveRolePurview(portalCompanyUserRoleBean.getPortalCompanyRoleId(), purviewIds);
		} catch (Exception e) {
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}

		return result;

	}

	public static CheckBoxTreeVo getAreaTree(List<CheckBoxTreeVo> list) {
		// 构造tree
		Map<String, CheckBoxTreeVo> roleMap = new LinkedHashMap<String, CheckBoxTreeVo>();
		for (CheckBoxTreeVo fsAreaTreeBean : list) {
			roleMap.put(fsAreaTreeBean.getPId(), fsAreaTreeBean);
		}

		CheckBoxTreeVo root = new CheckBoxTreeVo();
		// 递归构造树
		Iterator<Map.Entry<String, CheckBoxTreeVo>> it = roleMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, CheckBoxTreeVo> entry = it.next();
			CheckBoxTreeVo tree = entry.getValue();
			tree.setTitle(tree.getName());
			tree.setChecked(tree.getIsChecked());
			if (tree.getParentId().equals("")) {// 如果是根节点
				root.getChildren().add(tree);
			} else {
				CheckBoxTreeVo parent = roleMap.get(tree.getParentId());// 根据父Id查询
				if (parent != null) {
					parent.getChildren().add(tree);
				}
			}
		}

		return root;
	}

	/**
	 * 查询所有角色
	 * @param request
	 * @param response
	 * @param bean
	 * @return
	 * @throws JSONException
	 *             ResultBean
	 * @Author Administrator
	 * @Date 2017年9月25日
	 */
	@RequestMapping(value = "/role/all",method= RequestMethod.POST)
	public @ResponseBody ResultBean roleAll(
			HttpServletRequest request, HttpServletResponse response,
			@RequestBody PortalCompanyRoleQueryBean bean){
		ResultBean result = new ResultBean(true, null);
		try {
			result.setObject(portalCompanyRoleService.queryRoleAll(bean.getRoleName()));
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			if (e instanceof ServiceException) {
				result.setErrorCode(e.getMessage());
			} else {
				result.setErrorCode(ResultStatus.SYS_ERROR.getCode());
			}
		}
		return result;
	}


}
